﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

namespace Enterprise.DataCMS.WebSiteExplorer
{
    public partial class Explorer : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
               
                string domain = Request.Url.GetLeftPart(UriPartial.Authority);
                Tree.Text = string.Format("<li class=\"root\" id=\"0\"><span>{1}</span><ul>\n\t{0}\n</ul></li>", CreateTree(SiteMap.RootNode, 0), domain);
            }
        }

        private string CreateTree(SiteMapNode nodes, int level)
        {
            string treedata = string.Empty;

            foreach (SiteMapNode node in nodes.ChildNodes)
            {
                if (level > 0)
                    return treedata;

                if (node.Key != null)
                {
                    treedata += CreateNode(node.Key, node.Title, node.HasChildNodes, node.Key);
                    if (node.HasChildNodes)
                        treedata += string.Format("\n\t{0}\n", CreateTree(node, level + 1));
                    treedata += "</li>\n";
                }
                else
                {
                    throw new Exception("ID is null");
                }
            }
            return treedata;
        }

        private string CreateNode(string id, string text, bool hasChildNodes, string parentnode)
        {
            string s = string.Empty;

            if (hasChildNodes)
            {
                s = "\n<li class=\"text\" id=\"" + id + "\">\n";
                s += "  <span>" + text + "</span>\n";
                s += "   <ul class=\"ajax\">\n";
                s += "      \t<li id=\"" + id + "\">{url:/WebSiteExplorer/Controls/TreeDataManager.ashx?action=getElementList&ownerEl=" + parentnode + "}</li>\n";
                s += "   </ul>\n";
            }
            else
            {
                s = "<li class='text' id=\"" + id + "\"><span>" + text + "</span>";
            }
            return s;
        }
    }
}
